﻿using System;
using System.Linq;
using System.Web.Mvc;
using Gp.Examples.FullCalendar.Core;
using Gp.Examples.FullCalendar.Core.Repository;
using Gp.Examples.FullCalendar.Infrastructure;

namespace Gp.Examples.FullCalendar.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (string.IsNullOrEmpty(User.Identity.Name))
                return View();

            return View("AuthIndex");
        }

        public ActionResult Calendar(string userId)
        {
            ViewData["MyEvents"] = false;

            if(User.Identity != null)
                ViewData["MyEvents"] = (userId == User.Identity.Name.ToLower());
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public JsonResult GetEvents(string userName, double start, double end)
        {
            //var userName = User.Identity.Name;
            if (string.IsNullOrWhiteSpace(userName))
            {
                Response.Write("nosess");
                return null;
            }

            var fromDate = ConvertFromUnixTimestamp(start);
            var toDate = ConvertFromUnixTimestamp(end);

            var eventRepository = Resolver.Resolve<IEventRepository>();
            var events = eventRepository.ListEventsForUser(userName, fromDate, toDate);

            var eventList = from e in events
                            select new
                            {
                                id = e.Id,
                                title = e.Title,
                                start = e.FromDate.ToString("s"),
                                end = e.ToDate.ToString("s"),
                                allDay = false
                            };
            var rows = eventList.ToArray();
            return Json(rows, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddEvent(string title, long dateStamp, int fromHours, int fromMinutes, int toHours, int toMinutes)
        {
            var userName = User.Identity.Name;
            if (string.IsNullOrEmpty(userName))
            {
                Response.Write("EXP");
                Response.End();
                return null;
            }

            var date = ConvertFromUnixTimestamp(dateStamp).Date;
            var fromDate = date.AddHours(fromHours).AddMinutes(fromMinutes);
            var toDate = date.AddHours(toHours).AddMinutes(toMinutes);

            var userRepository = Resolver.Resolve<IUserRepository>();
            var eventRepository = Resolver.Resolve<IEventRepository>();

            var e = new Event();
            e.FromDate = (fromDate <= toDate ? fromDate : toDate);
            e.ToDate = (toDate >= fromDate ? toDate : fromDate);
            e.User = userRepository.GetUserByUserName(userName);
            e.Title = title;
            eventRepository.Save(e);

            Response.Write("OK");
            Response.End();
            return null;
        }

        public ActionResult DeleteEvent(int eventId)
        {
            var userName = User.Identity.Name;
            var repository = Resolver.Resolve<IEventRepository>();
            var evt = repository.GetEventById(eventId);

            if (evt.User.UserName != userName)
                return null;

            repository.Delete(evt);
            return null;
        }

        private static DateTime ConvertFromUnixTimestamp(double timestamp)
        {
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return origin.AddSeconds(timestamp);
        }

        private double ConvertToUnixTimestamp(DateTime date)
        {
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            TimeSpan diff = date - origin;
            return Math.Floor(diff.TotalSeconds);
        }
    }
}
